#!/usr/bin/env python

import sys
import os.path
import os
import shutil
import time
import csv
import traceback
import django
import mimetypes

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")


from home.models import Image as MIImage
from home.files import createFolder, getMetaInformation, convertFormat

def printUsage(isError):
    if isError:
        print 'Invalid arguments'

    print 'Usage: '
    print '\tImport datas: '
    print 'import_data.py ',
    print 'ImageDirPath CSVDirPath'
    print '\tShow this message: '
    print 'import_data.py -h'


def csvDirHandler(csvPath):
    isSuccessful = True;
    basePath = createFolder('csv')
    for parentDir, dirnames, filenames in os.walk(csvPath):
        for filename in filenames:
            fileType = os.path.splitext(filename)[1]
            #print fileType
            if fileType == '.csv':
                shutil.move(parentDir+filename, basePath)
                #print basePath + filename
                isSuccessful = getMetaInformation(basePath + filename) and isSuccessful
    return isSuccessful

def imageDirHandler(imagePath):
    isSuccessful = True
    basePath = createFolder('image')
    for parentDir, dirnames, filenames in os.walk(imagePath):
        for filename in filenames:
            if filename.lower().endswith('tif'):
                shutil.move(parentDir + filename, basePath)
                try:
                    print filename
                    imageObject     = MIImage.objects.get(file_name=filename)
                    imageFilePath   = basePath + filename
                    imageObject.image_file_location = convertFormat(imageFilePath)
                    imageObject.save()
                except:
                    print "failed"
                    pass
    return isSuccessful


def importAllDatas(imagePath, csvPath):
    isCSVCorrect = csvDirHandler(csvPath)
    isImageCorrect = imageDirHandler(imagePath)

    return isCSVCorrect and isImageCorrect

def mainFunc():
    if len(sys.argv) == 2:
        tempDirPath = sys.argv[1] if sys.argv[1].endswith('/') else sys.argv[1] + '/'
        imageDirPath = tempDirPath + '/image/'
        csvDirPath = tempDirPath + '/csv/'
        isDataCorrect = importAllDatas(imageDirPath, csvDirPath)
        if isDataCorrect:
            print 'import successed'
        else:
            print 'import failed'
    else:
        printUsage(True)



if __name__ == '__main__':
    django.setup()
    mainFunc()
